const site = "http://172.23.246.222:8080";

let app;

let globalData = {
  publicKey: `-----BEGIN PUBLIC KEY-----
  MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN7k/py7FRgtn0qCERgqQQ89FI
  kOuBRnspM5aGkvGifJabz+EXDj5IHElRv8wpzO1kSMtBmakwyj6XdbksAa/x8Y6i
  q+DY5PxxkgH1FE3BIqyfGBI9GGCAjWzrrAj7UKM0Ar9fMQv6wGMrI60YmbB9AD6x
  B+tcX/SK8x6TPFevxQIDAQAB
  -----END PUBLIC KEY-----
  `,
  encryptor: new JSEncrypt()
};

// 初始化
(function () {
  globalData.encryptor.setPublicKey(globalData.publicKey);
})();

function requestCheckedActivityList(page, size, success, fail) {
  "user strict"
  console.log(`G$c Func=getCheckedActivityList, Msg=CallStart`);
  axios.get(`${site}/admins/1/check?page=${page}&size=${size}`, {
      headers: {
        'Authorization': `Bearer:${app.token}`
      }
    })
    .then(function (res) {
      if (success instanceof Function) {
        success(res);
      }
    })
    .catch(function (error) {
      if (fail instanceof Function) {
        fail(error);
      }
    });
}

const login = {
  template: '#login',
  data() {
    return {
      account: null,
      password: null
    }
  },
  methods: {
    login: function () {
      'use strict'
      if (this.account == null || this.password == null) {
        alert("账号密码不能为空哦！OvO");
        return;
      }

      globalData.account = this.account;

      // app.token = '1';
      // app.id = 1;
      // app.$router.push('home');

      axios.post(`${site}/login`, {
          account: this.account,
          password: globalData.encryptor.encrypt(this.password)
        })
        .then(function (res) {
          if (res.status == 200) {
            console.log(res);
            let data = res.data;
            let result = data.result;
            app.id = result.id;
            app.token = result.token;

            // 获取个人信息
            axios.get(`${site}/users/${result.id}`, {}, {
                headers: {
                  'Authorization': `Bearer:${app.token}`
                }
              })
              .then(function (res) {
                console.log(res);
                if (res.status == 200) {
                  let data = res.data;
                  let result = data.result;
                  if (data.error_code == 0) {
                    // 设置个人信息并跳转
                    globalData.user = result;
                    app.$router.push("home");
                  }
                } else {
                  alert(`获取个人信息失败，error_code=${res.data.error_code}`);
                }
              })
              .catch(function (error) {
                console.log(`G$c Func=login.login, Msg=Fail to send get user info post`);
                console.log(error);
                alert("获取个人信息请求发送失败")
              });
          } else {
            console.log(`G$c Func=login.login, Msg={status=${res.status}}`);
            alert(`Fail to login, status=${res.status}`);
          }
        })
        .catch(function (error) {
          console.log(error);
          alert(`账号密码不正确`);
        });
    }
  },
}
const home = {
  template: '#home'
}
const pageMain = {
  template: '#page-main'
}
const pageCheck = {
  template: '#page-check',
  data: function () {
    return {
      activityList: app.activityList,
      showDetail: false,
      detail: null,
      currentCheckPage: app.currentCheckPage
    }
  },
  methods: {
    seeDetail: function (activity) {
      this.detail = activity.activityProfile;
      this.showDetail = true;
    },
    // 通过和拒绝审核
    pass: function (id, index) {
      axios.put(`${site}/admins/1/check?activityId=${id}&state=1`, {}, {
          headers: {
            'Authorization': `Bearer:${app.token}`
          }
        })
        .then(function (res) {
          if (res.status == 200) {
            console.log(res);
            let data = res.data;
            if (data.error_code == 0) {
              // 删除
              app.activityList.splice(index, 1);
            } else {
              console.log(`G$c Func=pageCheck.pass, Msg={error_code:${data.error_code}}`);
            }
          } else {
            console.log(`G$c Func=pageCheck.pass, Msg={status:${res.status}}`);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    deny: function (id, index) {
      axios.put(`${site}/admins/1/check?activityId=${id}&state=0`, {}, {
          headers: {
            'Authorization': `Bearer:${app.token}`
          }
        })
        .then(function (res) {
          if (res.status == 200) {
            console.log(res);
            let data = res.data;
            if (data.error_code == 0) {
              // 删除
              app.activityList.splice(index, 1);
            } else {
              console.log(`G$c Func=pageCheck.deny, Msg={error_code:${data.error_code}}`);
            }
          } else {
            console.log(`G$c Func=pageCheck.deny, Msg={status:${res.status}}`);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 下一页
    nextPage: function () {
      console.log(`G$c Func=pageCheck.nextPage, Msg=CallStart`);
      // 请求
      requestCheckedActivityList(app.currentCheckPage + 1, 10, res => {
        // Success
        console.log(res);
        if (res.status == 200) {
          app.activityList = res.data.result;
          app.currentCheckPage++;
        }
      }, res => {
        // Fail
        console.log(res);
      });
    },
    // 上一页
    prePage: function () {
      console.log(`G$c Func=pageCheck.nextPage, Msg=CallStart`);
      requestCheckedActivityList(app.currentCheckPage - 1, 10, res => {
        // Success
        console.log(res);
        if (res.status == 200) {
          app.activityList = res.data.result;
          app.currentCheckPage--;
        }
      }, res => {
        // Fail
        console.log(res);
      });
    }
  }
}
const pageSet = {
  template: '#page-set'
}

const routes = [{
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: login
  },
  {
    path: '/home',
    component: home,
    meta: {
      requireAuth: true
    },
    children: [{
        path: 'main',
        component: pageMain,
        meta: {
          requireAuth: true
        }
      },
      {
        path: 'check',
        component: pageCheck,
        meta: {
          requireAuth: true
        }
      },
      {
        path: 'set',
        component: pageSet,
        meta: {
          requireAuth: true
        }
      },
      {
        path: '/home',
        redirect: 'main'
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'hash',
  routes
})

app = new Vue({
  el: '#app',
  data: {
    token: null,
    id: null,
    currentCheckPage: 0,
    activityList: [{
      activityId: 0,
      activityName: "LOL战斗之夜",
      activityLocation: "活动地点",
      activityStart: "2020-09-11", //long
      activityEnd: "2020-09-11", //long
      activityProfile: "LOL战斗之夜的活动简介。LOL战斗之夜的活动简介。LOL战斗之夜的活动简介。",
      activityKind: "活动类型", //枚举类：STUDY,PLAY,SPORTS,READING,OTHERS
      activityPic: "活动图片",
      joinNum: "活动参与人数", //int
      publisherId: "活动发布者id"
    }, {
      activityId: 1,
      activityName: "裴仁杰相亲活动",
      activityLocation: "活动地点",
      activityStart: "2020-09-11", //long
      activityEnd: "2020-09-11", //long
      activityProfile: "活动简介",
      activityKind: "活动类型", //枚举类：STUDY,PLAY,SPORTS,READING,OTHERS
      activityPic: "活动图片",
      joinNum: "活动参与人数", //int
      publisherId: "活动发布者id"
    }]
  },
  methods: {

  },
  router: router
})

router.beforeEach((to, from, next) => {
  console.log(`G$c Func=router.beforeEnter, Msg=CallStart`);
  if (to.meta.requireAuth) {
    if (app.token != null && app.id != null) {
      if ("/home/check" == to.fullPath) {
        console.log(`G$c Func=router.beforeEach, Msg=Send get activityList`);
        // 执行请求
        axios.get(`${site}/admins/1/check?page=0&size=10`, {
            headers: {
              'Authorization': `Bearer:${app.token}`
            }
          })
          .then(function (res) {
            console.log(res);
            let activityList = res.data.result;
            app.activityList = activityList;
            next();
          })
          .catch(function (error) {
            console.log(error);
          });
        next();
      } else {
        next();
      }
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      })
    }
  } else {
    next();
  }
})